/**
 * 压缩图片
 * @param base64String base64图片
 * @param w 图片宽度
 * @param quality 压缩系数0-1之间
 * @returns 压缩后的base64
 */
export function compress(base64String: string, w = 50, quality = 0.6) {
  const newImage = new Image();
  let imgWidth, imgHeight;
  const promise = new Promise((resolve) => (newImage.onload = resolve));
  newImage.src = base64String;
  return promise.then(() => {
    imgWidth = newImage.width;
    imgHeight = newImage.height;
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    if (Math.max(imgWidth, imgHeight) > w) {
      if (imgWidth > imgHeight) {
        canvas.width = w;
        canvas.height = (w * imgHeight) / imgWidth;
      } else {
        canvas.height = w;
        canvas.width = (w * imgWidth) / imgHeight;
      }
    } else {
      canvas.width = imgWidth;
      canvas.height = imgHeight;
    }
    ctx?.clearRect(0, 0, canvas.width, canvas.height);
    ctx?.drawImage(newImage, 0, 0, canvas.width, canvas.height);
    const base64 = canvas.toDataURL('image/jpeg', quality);
    return base64;
  });
}
